package com.cardone.platform.usercenter.controller;

import java.util.List;
import java.util.Map;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.cardone.common.dto.PaginationDto;
import com.cardone.context.Constants;
import com.cardone.platform.usercenter.dto.UsOrgTranslateDto;
import com.cardone.platform.usercenter.dto.UserActivationDto;
import com.cardone.platform.usercenter.dto.UserDto;
import com.cardone.platform.usercenter.service.UsercenterService;
import com.cardone.platform.usercenter.validator.UsOrgTranslateValidator;
import com.cardone.platform.usercenter.validator.UserActivationValidator;
import com.cardone.platform.usercenter.validator.UserValidator;
import com.cardone.platform.usercenter.vo.UserVo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 用户
 * 
 * @author yaoht
 */
@Setter
@Slf4j
@RequestMapping(UserController.Paths.ROOT)
@Controller
public class UserController {
	/**
	 * models集合
	 * 
	 * @author yaoht
	 * 
	 */
	public enum models {
		/**
		 * 消息
		 */
		message,

		/**
		 * 用户
		 */
		user,

		/**
		 * 用户激活
		 */
		userActivation,

		/**
		 * 用户组织调动
		 */
		usOrgTranslate;
	}

	/**
	 * 路径集合
	 * 
	 * @author yaoht
	 * 
	 */
	public enum Paths {
		/**
		 * 用户主界面
		 */
		index,

		/**
		 * 用户组织调动编辑视图路径
		 */
		US_ORG_TRANSLATEEdit("usOrgTranslate/edit"),

		/**
		 * 用户组织调动主界面视图路径
		 */
		US_ORG_TRANSLATEIndex("usOrgTranslate/index"),

		/**
		 * 用户组织调动编辑视图路径
		 */
		US_ORG_TRANSLATENew("usOrgTranslate/new"),

		/**
		 * 用户组织调动查看编辑视图路径
		 */
		US_ORG_TRANSLATEView("usOrgTranslate/view"),

		/**
		 * 用户激活编辑视图路径
		 */
		USER_ACTIVATIONEdit("userActivation/edit"),

		/**
		 * 用户激活主界面视图路径
		 */
		USER_ACTIVATIONIndex("userActivation/index"),

		/**
		 * 用户激活编辑视图路径
		 */
		USER_ACTIVATIONNew("userActivation/new"),

		/**
		 * 用户激活查看编辑视图路径
		 */
		USER_ACTIVATIONView("userActivation/view"),

		/**
		 * 用户编辑视图路径
		 */
		USEREdit("user/edit"),

		/**
		 * 用户主界面视图路径
		 */
		USERIndex("user/index"),

		/**
		 * 用户编辑视图路径
		 */
		USERNew("user/new"),

		/**
		 * 用户查看编辑视图路径
		 */
		USERView("user/view");

		/**
		 * 用户视图根目录
		 */
		public static final String ROOT = "/platform/usercenter/user/";

		/**
		 * 路径
		 */
		private final String path;

		/**
		 * 构建
		 * 
		 */
		private Paths() {
			this.path = Paths.ROOT + this.name();
		}

		/**
		 * 构建
		 * 
		 * @param path
		 *            路径
		 */
		private Paths(final String path) {
			this.path = Paths.ROOT + path;
		}

		/**
		 * 获取
		 * 
		 * @return 路径
		 */
		public String path() {
			return this.path;
		}
	}

	/**
	 * 用户激活验证
	 */
	@Qualifier(UserActivationValidator.BEAN_ID)
	@Autowired(required = false)
	public Validator userActivationValidator;

	/**
	 * 用户服务
	 */
	@Qualifier(UsercenterService.BEAN_ID)
	@Autowired(required = false)
	private UsercenterService usercenterService;

	/**
	 * 用户验证
	 */
	@Qualifier(UserValidator.BEAN_ID)
	@Autowired(required = false)
	public Validator userValidator;

	/**
	 * 用户组织调动验证
	 */
	@Qualifier(UsOrgTranslateValidator.BEAN_ID)
	@Autowired(required = false)
	public Validator usOrgTranslateValidator;

	/**
	 * 用户激活：删除
	 * 
	 * @param userVo
	 *            用户激活视图对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "userActivation/delete.json" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> userActivationDelete(final UserVo userVo) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.usercenterService.getUserService().deleteUserActivationByIds(userVo.getUserActivation());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (UserController.log.isDebugEnabled()) {
				UserController.log.debug(e.getMessage(), e);
			}
		}

		return jsonMap;
	}

	/**
	 * 用户激活：编辑
	 * 
	 * @param userVo
	 *            用户激活视图对象
	 * @param model
	 *            上下文映射
	 * @return 用户激活编辑视图路径
	 */
	@RequestMapping(value = { "userActivation/edit.html" }, method = RequestMethod.GET)
	public String userActivationEdit(final UserVo userVo, final Model model) {
		final UserActivationDto userActivation = this.usercenterService.getUserService().findUserActivationById(
		        userVo.getUserActivation());

		model.addAttribute(UserController.models.userActivation.name(), userActivation);

		return UserController.Paths.USER_ACTIVATIONEdit.path();
	}

	/**
	 * 用户激活：主界面
	 * 
	 * @return 用户激活主界面视图路径
	 */
	@RequestMapping(value = { "userActivation/index.html" })
	public String userActivationIndex() {
		return UserController.Paths.USER_ACTIVATIONIndex.path();
	}

	/**
	 * 用户激活：主界面分页查询
	 * 
	 * @param userVo
	 *            用户激活视图对象
	 * @return 分页数据，json格式
	 */
	@RequestMapping(value = { "userActivation/index/pagination.json" })
	@ResponseBody
	public Map<String, Object> userActivationIndexPagination(final UserVo userVo) {
		final PaginationDto<UserActivationDto> userActivationPagination = this.usercenterService.getUserService()
		        .paginationUserActivationByCode(userVo.getUserActivation());

		final Map<String, Object> userActivationPaginationMap = Maps.newHashMap();

		userActivationPaginationMap.put(Constants.total.stringValue(), userActivationPagination.getTotalSize());
		userActivationPaginationMap.put(Constants.rows.stringValue(), userActivationPagination.getDataList());

		return userActivationPaginationMap;
	}

	/**
	 * 用户激活：新增
	 * 
	 * @param userVo
	 *            用户激活视图对象
	 * @param model
	 *            上下文映射
	 * @return 用户激活编辑视图路径
	 */
	@RequestMapping(value = { "userActivation/new.html" }, method = RequestMethod.GET)
	public String userActivationNew(final UserVo userVo, final Model model) {
		model.addAttribute(UserController.models.userActivation.name(), userVo.getUserActivation());

		return UserController.Paths.USER_ACTIVATIONNew.path();
	}

	/**
	 * 用户激活：保存
	 * 
	 * @param userVo
	 *            用户激活视图对象
	 * @param bindingResult
	 *            绑定对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "userActivation/save.txt" }, method = RequestMethod.POST)
	@ResponseBody
	public String userActivationSave(final UserVo userVo, BindingResult bindingResult) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.userActivationValidator.validate(userVo.getUserActivation(), bindingResult);

			if (bindingResult.hasErrors()) {
				List<String> messageList = Lists.newArrayList();

				for (final ObjectError objectError : bindingResult.getAllErrors()) {
					messageList.add(objectError.getDefaultMessage());
				}

				String message = StringUtils.join(messageList, org.apache.commons.lang3.StringUtils.EMPTY);

				throw new Exception(message);
			}

			this.usercenterService.getUserService().saveUserActivationByIdOrCode(userVo.getUserActivation());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (UserController.log.isDebugEnabled()) {
				UserController.log.debug(e.getMessage(), e);
			}
		}

		return JSON.toJSONString(jsonMap);
	}

	/**
	 * 用户激活：更新
	 * 
	 * @param userVo
	 *            用户激活视图对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "userActivation/update.json" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> userActivationUpdate(final UserVo userVo) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.usercenterService.getUserService().updateUserActivationByIds(userVo.getUserActivation());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (UserController.log.isDebugEnabled()) {
				UserController.log.debug(e.getMessage(), e);
			}
		}

		return jsonMap;
	}

	/**
	 * 用户激活：验证
	 * 
	 * @param userVo
	 *            用户激活视图对象
	 * @return 验证结果
	 */
	@RequestMapping(value = { "userActivation/validationByCode.json" })
	@ResponseBody
	public Boolean userActivationValidationByCode(final UserVo userVo) {
		try {
			final int count = this.usercenterService.getUserService().readUserActivationByCodeNqId(userVo.getUserActivation());

			return (count < 1);
		} catch (final Exception e) {
			if (UserController.log.isDebugEnabled()) {
				UserController.log.debug(e.getMessage(), e);
			}
		}

		return false;
	}

	/**
	 * 用户激活：查看
	 * 
	 * @param userVo
	 *            用户激活视图对象
	 * @param model
	 *            上下文映射
	 * @return 用户激活查看编辑视图路径
	 */
	@RequestMapping(value = { "userActivation/view.html" }, method = RequestMethod.GET)
	public String userActivationView(final UserVo userVo, final Model model) {
		final UserActivationDto userActivation = this.usercenterService.getUserService().findUserActivationById(
		        userVo.getUserActivation());

		model.addAttribute(UserController.models.userActivation.name(), userActivation);

		return UserController.Paths.USER_ACTIVATIONView.path();
	}

	/**
	 * 用户：删除
	 * 
	 * @param userVo
	 *            用户视图对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "user/delete.json" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> userDelete(final UserVo userVo) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.usercenterService.getUserService().deleteUserByIds(userVo.getUser());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (UserController.log.isDebugEnabled()) {
				UserController.log.debug(e.getMessage(), e);
			}
		}

		return jsonMap;
	}

	/**
	 * 用户：编辑
	 * 
	 * @param userVo
	 *            用户视图对象
	 * @param model
	 *            上下文映射
	 * @return 用户编辑视图路径
	 */
	@RequestMapping(value = { "user/edit.html" }, method = RequestMethod.GET)
	public String userEdit(final UserVo userVo, final Model model) {
		final UserDto user = this.usercenterService.getUserService().findUserById(userVo.getUser());

		model.addAttribute(UserController.models.user.name(), user);

		return UserController.Paths.USEREdit.path();
	}

	/**
	 * 用户：主界面
	 * 
	 * @return 用户主界面视图路径
	 */
	@RequestMapping(value = { "user/index.html" })
	public String userIndex() {
		return UserController.Paths.USERIndex.path();
	}

	/**
	 * 用户：主界面分页查询
	 * 
	 * @param userVo
	 *            用户视图对象
	 * @return 分页数据，json格式
	 */
	@RequestMapping(value = { "user/index/pagination.json" })
	@ResponseBody
	public Map<String, Object> userIndexPagination(final UserVo userVo) {
		final PaginationDto<UserDto> userPagination = this.usercenterService.getUserService().paginationUserByCode(userVo.getUser());

		final Map<String, Object> userPaginationMap = Maps.newHashMap();

		userPaginationMap.put(Constants.total.stringValue(), userPagination.getTotalSize());
		userPaginationMap.put(Constants.rows.stringValue(), userPagination.getDataList());

		return userPaginationMap;
	}

	/**
	 * 用户：新增
	 * 
	 * @param userVo
	 *            用户视图对象
	 * @param model
	 *            上下文映射
	 * @return 用户编辑视图路径
	 */
	@RequestMapping(value = { "user/new.html" }, method = RequestMethod.GET)
	public String userNew(final UserVo userVo, final Model model) {
		model.addAttribute(UserController.models.user.name(), userVo.getUser());

		return UserController.Paths.USERNew.path();
	}

	/**
	 * 用户：保存
	 * 
	 * @param userVo
	 *            用户视图对象
	 * @param bindingResult
	 *            绑定对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "user/save.txt" }, method = RequestMethod.POST)
	@ResponseBody
	public String userSave(final UserVo userVo, BindingResult bindingResult) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.userValidator.validate(userVo.getUser(), bindingResult);

			if (bindingResult.hasErrors()) {
				List<String> messageList = Lists.newArrayList();

				for (final ObjectError objectError : bindingResult.getAllErrors()) {
					messageList.add(objectError.getDefaultMessage());
				}

				String message = StringUtils.join(messageList, org.apache.commons.lang3.StringUtils.EMPTY);

				throw new Exception(message);
			}

			this.usercenterService.getUserService().saveUserByIdOrCode(userVo.getUser());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (UserController.log.isDebugEnabled()) {
				UserController.log.debug(e.getMessage(), e);
			}
		}

		return JSON.toJSONString(jsonMap);
	}

	/**
	 * 用户：更新
	 * 
	 * @param userVo
	 *            用户视图对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "user/update.json" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> userUpdate(final UserVo userVo) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.usercenterService.getUserService().updateUserByIds(userVo.getUser());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (UserController.log.isDebugEnabled()) {
				UserController.log.debug(e.getMessage(), e);
			}
		}

		return jsonMap;
	}

	/**
	 * 用户：验证
	 * 
	 * @param userVo
	 *            用户视图对象
	 * @return 验证结果
	 */
	@RequestMapping(value = { "user/validationByCode.json" })
	@ResponseBody
	public Boolean userValidationByCode(final UserVo userVo) {
		try {
			final int count = this.usercenterService.getUserService().readUserByCodeNqId(userVo.getUser());

			return (count < 1);
		} catch (final Exception e) {
			if (UserController.log.isDebugEnabled()) {
				UserController.log.debug(e.getMessage(), e);
			}
		}

		return false;
	}

	/**
	 * 用户：查看
	 * 
	 * @param userVo
	 *            用户视图对象
	 * @param model
	 *            上下文映射
	 * @return 用户查看编辑视图路径
	 */
	@RequestMapping(value = { "user/view.html" }, method = RequestMethod.GET)
	public String userView(final UserVo userVo, final Model model) {
		final UserDto user = this.usercenterService.getUserService().findUserById(userVo.getUser());

		model.addAttribute(UserController.models.user.name(), user);

		return UserController.Paths.USERView.path();
	}

	/**
	 * 用户组织调动：删除
	 * 
	 * @param userVo
	 *            用户组织调动视图对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "usOrgTranslate/delete.json" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> usOrgTranslateDelete(final UserVo userVo) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.usercenterService.getUserService().deleteUsOrgTranslateByIds(userVo.getUsOrgTranslate());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (UserController.log.isDebugEnabled()) {
				UserController.log.debug(e.getMessage(), e);
			}
		}

		return jsonMap;
	}

	/**
	 * 用户组织调动：编辑
	 * 
	 * @param userVo
	 *            用户组织调动视图对象
	 * @param model
	 *            上下文映射
	 * @return 用户组织调动编辑视图路径
	 */
	@RequestMapping(value = { "usOrgTranslate/edit.html" }, method = RequestMethod.GET)
	public String usOrgTranslateEdit(final UserVo userVo, final Model model) {
		final UsOrgTranslateDto usOrgTranslate = this.usercenterService.getUserService().findUsOrgTranslateById(
		        userVo.getUsOrgTranslate());

		model.addAttribute(UserController.models.usOrgTranslate.name(), usOrgTranslate);

		return UserController.Paths.US_ORG_TRANSLATEEdit.path();
	}

	/**
	 * 用户组织调动：主界面
	 * 
	 * @return 用户组织调动主界面视图路径
	 */
	@RequestMapping(value = { "usOrgTranslate/index.html" })
	public String usOrgTranslateIndex() {
		return UserController.Paths.US_ORG_TRANSLATEIndex.path();
	}

	/**
	 * 用户组织调动：主界面分页查询
	 * 
	 * @param userVo
	 *            用户组织调动视图对象
	 * @return 分页数据，json格式
	 */
	@RequestMapping(value = { "usOrgTranslate/index/pagination.json" })
	@ResponseBody
	public Map<String, Object> usOrgTranslateIndexPagination(final UserVo userVo) {
		final PaginationDto<UsOrgTranslateDto> usOrgTranslatePagination = this.usercenterService.getUserService()
		        .paginationUsOrgTranslateByCode(userVo.getUsOrgTranslate());

		final Map<String, Object> usOrgTranslatePaginationMap = Maps.newHashMap();

		usOrgTranslatePaginationMap.put(Constants.total.stringValue(), usOrgTranslatePagination.getTotalSize());
		usOrgTranslatePaginationMap.put(Constants.rows.stringValue(), usOrgTranslatePagination.getDataList());

		return usOrgTranslatePaginationMap;
	}

	/**
	 * 用户组织调动：新增
	 * 
	 * @param userVo
	 *            用户组织调动视图对象
	 * @param model
	 *            上下文映射
	 * @return 用户组织调动编辑视图路径
	 */
	@RequestMapping(value = { "usOrgTranslate/new.html" }, method = RequestMethod.GET)
	public String usOrgTranslateNew(final UserVo userVo, final Model model) {
		model.addAttribute(UserController.models.usOrgTranslate.name(), userVo.getUsOrgTranslate());

		return UserController.Paths.US_ORG_TRANSLATENew.path();
	}

	/**
	 * 用户组织调动：保存
	 * 
	 * @param userVo
	 *            用户组织调动视图对象
	 * @param bindingResult
	 *            绑定对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "usOrgTranslate/save.txt" }, method = RequestMethod.POST)
	@ResponseBody
	public String usOrgTranslateSave(final UserVo userVo, BindingResult bindingResult) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.usOrgTranslateValidator.validate(userVo.getUsOrgTranslate(), bindingResult);

			if (bindingResult.hasErrors()) {
				List<String> messageList = Lists.newArrayList();

				for (final ObjectError objectError : bindingResult.getAllErrors()) {
					messageList.add(objectError.getDefaultMessage());
				}

				String message = StringUtils.join(messageList, org.apache.commons.lang3.StringUtils.EMPTY);

				throw new Exception(message);
			}

			this.usercenterService.getUserService().saveUsOrgTranslateByIdOrCode(userVo.getUsOrgTranslate());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (UserController.log.isDebugEnabled()) {
				UserController.log.debug(e.getMessage(), e);
			}
		}

		return JSON.toJSONString(jsonMap);
	}

	/**
	 * 用户组织调动：更新
	 * 
	 * @param userVo
	 *            用户组织调动视图对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "usOrgTranslate/update.json" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> usOrgTranslateUpdate(final UserVo userVo) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.usercenterService.getUserService().updateUsOrgTranslateByIds(userVo.getUsOrgTranslate());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (UserController.log.isDebugEnabled()) {
				UserController.log.debug(e.getMessage(), e);
			}
		}

		return jsonMap;
	}

	/**
	 * 用户组织调动：验证
	 * 
	 * @param userVo
	 *            用户组织调动视图对象
	 * @return 验证结果
	 */
	@RequestMapping(value = { "usOrgTranslate/validationByCode.json" })
	@ResponseBody
	public Boolean usOrgTranslateValidationByCode(final UserVo userVo) {
		try {
			final int count = this.usercenterService.getUserService().readUsOrgTranslateByCodeNqId(userVo.getUsOrgTranslate());

			return (count < 1);
		} catch (final Exception e) {
			if (UserController.log.isDebugEnabled()) {
				UserController.log.debug(e.getMessage(), e);
			}
		}

		return false;
	}

	/**
	 * 用户组织调动：查看
	 * 
	 * @param userVo
	 *            用户组织调动视图对象
	 * @param model
	 *            上下文映射
	 * @return 用户组织调动查看编辑视图路径
	 */
	@RequestMapping(value = { "usOrgTranslate/view.html" }, method = RequestMethod.GET)
	public String usOrgTranslateView(final UserVo userVo, final Model model) {
		final UsOrgTranslateDto usOrgTranslate = this.usercenterService.getUserService().findUsOrgTranslateById(
		        userVo.getUsOrgTranslate());

		model.addAttribute(UserController.models.usOrgTranslate.name(), usOrgTranslate);

		return UserController.Paths.US_ORG_TRANSLATEView.path();
	}
}
